package service

import (
	"backend_api/internal/global"
	"backend_api/internal/model"
	"backend_api/internal/model/request"
	"errors"
)

type ToolService struct{}

// GetToolList 获取工具列表
func (s *ToolService) GetToolList(req *request.ToolListReq) (list []model.Tool, total int64, err error) {
	db := global.DB.Model(&model.Tool{}).Preload("Category")

	// 条件查询
	if req.Name != "" {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.CategoryID > 0 {
		db = db.Where("category_id = ?", req.CategoryID)
	}
	if *req.Status >= 0 {
		db = db.Where("status = ?", *req.Status)
	}
	// 获取总数
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	// 分页查询
	err = db.Limit(req.PageSize).Offset((req.Page - 1) * req.PageSize).
		Order("id DESC").
		Find(&list).Error
	return
}

// AddTool 添加工具
func (s *ToolService) AddTool(req *request.ToolAddReq) error {
	// 检查名称是否存在
	var count int64
	if err := global.DB.Model(&model.Tool{}).Where("name = ?", req.Name).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("工具名称已存在")
	}

	// 检查分类是否存在
	var category model.ToolCategory
	if err := global.DB.First(&category, req.CategoryID).Error; err != nil {
		return errors.New("分类不存在")
	}

	// 创建工具
	tool := &model.Tool{
		Name:        req.Name,
		Description: req.Description,
		CategoryID:  req.CategoryID,
		Sort:        req.Sort,
		Status:      req.Status,
	}

	return global.DB.Create(tool).Error
}

// UpdateTool 更新工具
func (s *ToolService) UpdateTool(req *request.ToolUpdateReq) error {
	// 检查工具是否存在
	var tool model.Tool
	if err := global.DB.First(&tool, req.ID).Error; err != nil {
		return errors.New("工具不存在")
	}

	// 检查名称是否重复（排除自身）
	var count int64
	if err := global.DB.Model(&model.Tool{}).
		Where("name = ? AND id != ?", req.Name, req.ID).
		Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("工具名称已存在")
	}

	// 检查分类是否存在
	var category model.ToolCategory
	if err := global.DB.First(&category, req.CategoryID).Error; err != nil && req.CategoryID > 0 {
		return errors.New("分类不存在")
	}

	// 更新工具
	if req.Name != "" {
		tool.Name = req.Name
	}
	tool.Description = req.Description
	if req.Name != "" {
		tool.CategoryID = req.CategoryID
	}
	if req.Status >= 0 {
		tool.Status = req.Status
	}
	if req.Sort >= 0 {
		tool.Sort = req.Sort
	}
	return global.DB.Save(&tool).Error
}

// DeleteTool 删除工具
func (s *ToolService) DeleteTool(req *request.ToolDeleteReq) error {
	return global.DB.Delete(&model.Tool{}, req.ID).Error
}

// UpdateStatus UpdateStatus
func (s *ToolService) UpdateStatus(req *request.ToolUpdateStatusReq) error {
	return global.DB.Model(&model.Tool{}).Where("id = ?", req.ID).Updates(map[string]interface{}{
		"status": req.Status,
	}).Error
}

// UpdateSort UpdateSort
func (s *ToolService) UpdateSort(req *request.ToolUpdateSortReq) error {
	return global.DB.Model(&model.Tool{}).Where("id = ?", req.ID).Updates(map[string]interface{}{
		"sort": req.Sort,
	}).Error
}
